<?php
namespace app\common\model;
use think\Model;
/**
 * 附近圈
 */
class Nearby extends Model {
	protected $insert = ['add_time'];
	protected function setAddTimeAttr(){
		return time();
	}


	/**
	 * [nearbyList 附近圈列表]
	 * @param  array   $where [description]
	 * @param  integer $p     [页码]
	 * @param  string  $order   [排序]
	 * @param  string  $lng   [当前用户经度]
	 * @param  string  $lat   [当前用户纬度]
	 * @return [type]         [description]
	 */
	public function nearbyList($where = [],$order = 'juli asc',$p = 1,$lng = '',$lat = '',$limit_start = 0, $limit_end = 0){
		$field = "n.id,video,image,title,collect_num,zan_num,n.add_time,nick_name,photo_path,sex,tag";

		if($lng !== '' && $lat !== ''){
			$field .= ",ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - from_lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(from_lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - from_lng * PI() / 180) / 2),2)))) AS juli";
		}
		$this->alias('n')->join(['bz_user'=>'u'],'n.user_id = u.id')
			->where($where)->where('n.status',1)
			->order($order);
        if($limit_start == 0 && $limit_end == 0){
            $this->limit(($p-1)*config('page_size'),config('page_size'));
        }else{
            $this->limit($limit_start,$limit_end);
        }
			
		$list = $this->field($field)->select();

		return $list;

	}


	/**
	 * [dataCheck 数据处理]
	 * @param  array   $list    [description]
	 * @param  integer $user_id [description]
	 * @return [type]           [description]
	 */
	public function dataCheck($list = [] ,$user_id = 0){
		$collectModel = db('collect');
        $zanModel = db('issue_zan');
		foreach($list as $key => $val){
            $list[$key]['is_ad'] = 0;
			$list[$key]['image'] = empty($val['image'])?[]:explode(',',$val['image']);
            $list[$key]['format_time'] = timeFormat($val['add_time']);
            $list[$key]['tag'] = empty($val['tag']) ? [] : explode(',',$val['tag']) ;
            if(isset($val['photo_path']) && $val['photo_path'] && strpos($val['photo_path'],'http') === false){
                $list[$key]['photo_path'] = config('http_server').$val['photo_path'];
            }
            $list[$key]['is_zan'] = $list[$key]['is_collect'] = 0;
            if($user_id > 0){
            	if($collectModel->where('foreign_key',$val['id'])->where('type',2)->where('user_id',$user_id)->find()){
                    $list[$key]['is_collect'] = 1;
                }
                if($zanModel->where('foreign_key',$val['id'])->where('type',2)->where('user_id',$user_id)->find()){
                    $list[$key]['is_zan'] = 1;
                }
            }
		}

		return $list;
	}
}
